#include "login_manager.h"

Login_Manager::Login_Manager(QObject *parent) :
	QObject(parent),
	get_msg(NULL),
    m_check_timer(NULL),
    m_group_auto_respond(false),
    m_private_auto_respond(false)
{
	robot = new Tuling_Robot;
	connect(robot, SIGNAL(respond(QString, QString)), this, SLOT(robot_respond(QString, QString)));

	send_msg = new Send_Msg;

    account = new Account_Qrcode;
    connect(account, SIGNAL(qrcode_changed(QString)), this, SLOT(uuid_ok(QString)));
}

void Login_Manager::uuid_ok(QString uuid)
{
    if(uuid.isNull()) {
        account->get();
        return;
    }
    account->deleteLater();

    m_uuid = uuid;

    scan_check = new Scan_Check(uuid);
    connect(scan_check, SIGNAL(error()), this, SLOT(scan_error()));
    connect(scan_check, SIGNAL(scanedAndConfirmed(QString)), this, SLOT(scan_ok(QString)));
}

void Login_Manager::scan_ok(QString redirect_uri)
{
    scan_check->deleteLater();

	qDebug() << __PRETTY_FUNCTION__ << redirect_uri;

	login_server = new Login_Server;
	connect(login_server, SIGNAL(infoChanged(QString, QString, QString)), this, SLOT(login_ok(QString, QString, QString)));

	login_server->getV2(redirect_uri);
}

void Login_Manager::scan_error()
{
    scan_check->deleteLater();

    account = new Account_Qrcode;
    connect(account, SIGNAL(qrcode_changed(QString)), this, SLOT(uuid_ok(QString)));
}

void Login_Manager::login_ok(QString uin, QString sid, QString ticket)
{
	login_server->deleteLater();

	m_uin = uin;
	m_sid = sid;

	qDebug() << "UIN:" << uin << "SID:" << sid << "TICKET:" << ticket;

    stat_report = new Stat_Report;
    stat_report->postV2(m_uuid);

	info_init = new Info_Init;
	connect(info_init, SIGNAL(init_ok(QString, QString, QString, QStringList, QString)), this, SLOT(init_ok(QString, QString, QString, QStringList, QString)));
	info_init->postV2(m_uin, m_sid, ticket);
}

void Login_Manager::init_ok(QString userName, QString nickName, QString skey, QStringList syncKey, QString device_id)
{
	info_init->deleteLater();

	m_loginUserName = userName;
	m_loginNickName = nickName;

    m_replace_str = "@" + m_loginNickName;
    const char flag_str[] = {0xE2, 0x80, 0x85};
    QByteArray temp = m_replace_str.toLocal8Bit();
    temp.append(flag_str);
    m_replace_str = QString(temp);

	m_skey = skey;
	m_sync_key = syncKey;
	m_device_id = device_id;

	contact_info = new Contact_Info;
	connect(contact_info, SIGNAL(contact_ok()), this, SLOT(contact_ok()));

	contact_info->postV2();
}

void Login_Manager::contact_ok()
{
    m_group_auto_respond = false;
    m_private_auto_respond = false;

	sync_check = new Sync_Check;
	connect(sync_check, SIGNAL(msg_state(bool)), this, SLOT(msg_state(bool)));
    connect(sync_check, SIGNAL(error()), this, SLOT(sync_error()));

	if(m_check_timer == NULL) {
		m_check_timer = new QTimer;
	}

    status_notify = new Status_Notify;
    status_notify->postV2(m_uin, m_sid, m_skey, m_device_id, m_loginUserName);

	sync_check->getV2(m_uin, m_sid, m_skey, m_device_id, m_sync_key);
}

void Login_Manager::timer_to_check()
{
	sync_check->getV2(m_uin, m_sid, m_skey, m_device_id, m_sync_key);
}

void Login_Manager::msg_state(bool has_newmsg)
{
	if(has_newmsg) {
		if(get_msg == NULL) {
			get_msg = new Get_Msg;
			connect(get_msg, SIGNAL(msg_ok(QStringList)), this, SLOT(msg_ok(QStringList)));
			connect(get_msg, SIGNAL(received_msg(int, QString, QString, QString)), this, SLOT(received_msg(int, QString, QString, QString)));
		}

		get_msg->postV2(m_uin, m_sid, m_skey, m_sync_key);
	}
	else {
        m_check_timer->singleShot(2000, this, SLOT(timer_to_check()));
	}
}

void Login_Manager::sync_error()
{
    sync_check->deleteLater();

    account = new Account_Qrcode;
    connect(account, SIGNAL(qrcode_changed(QString)), this, SLOT(uuid_ok(QString)));
}

void Login_Manager::received_msg(int createTime, QString fromUserNameStr, QString toUserNameStr, QString content)
{
	if(fromUserNameStr == m_loginUserName) {
        QString to_nickName = contact_info->getNickName(toUserNameStr);

        // 我从手机端发出去的
        qDebug() << QDateTime::fromTime_t(createTime).toString("hh:mm:ss") << "[" << to_nickName << "] <---" << content;

        if(content.startsWith("机器人开启")) {
            if(toUserNameStr.startsWith("@@")) {
                m_group_auto_respond = true;
                send_msg_to_user(toUserNameStr, "温馨提示：[群组]机器人已开启。");
            }
            else {
                if(toUserNameStr == "filehelper") {
                    m_private_auto_respond = true;
                    send_msg_to_user(toUserNameStr, "温馨提示：[私人]机器人已开启。");
                }
            }
        }
        else if(content.startsWith("机器人关闭")) {
            if(toUserNameStr.startsWith("@@")) {
                m_group_auto_respond = false;
                send_msg_to_user(toUserNameStr, "温馨提示：[群组]机器人已关闭。");
            }
            else {
                if(toUserNameStr == "filehelper") {
                    m_private_auto_respond = false;
                    send_msg_to_user(toUserNameStr, "温馨提示：[私人]机器人已关闭。");
                }
            }
        }
	}
	else if(toUserNameStr == m_loginUserName) {
		QString from_nickName = contact_info->getNickName(fromUserNameStr);

		// 发给我的

		// 1.群消息
		if(fromUserNameStr.startsWith("@@")) {
			QString senderName;
			QString m_senderId;

			// 1.提取发言人
			int index = content.indexOf(":<br/>");
			if(index < 0) {
				qDebug() << "~~~~~~~~~~~~~~~~search sender error.~~~~~~~~~~~~~~~~~";

				// TODO:
			}
			else {
				m_senderId = content.left(index);
				senderName = contact_info->getNickName(m_senderId);

				index += (sizeof(":<br/>") - 1);
				content = content.mid(index);
			}

#if 0       // 只能自己开关机器人
            if(content.startsWith("机器人")) {
                if(content.length() == 3) {
                    send_msg_to_user(fromUserNameStr, "温馨提示：回复\"机器人开启/关闭\"来开启或者关闭机器人聊天，" \
                                                      "当开启机器人聊天后，回复\"机器人:+聊天内容\"即可和机器人聊天了，请注意文明聊天。", true);
                }
                else if(content.startsWith("机器人:") || content.startsWith("机器人：")) {
                    // 有人和机器人说话
                    if(m_auto_respond)
                        robot->post(fromUserNameStr, m_senderId, content.mid(4));
                }
                else if(content.startsWith("机器人开启")) {
                    m_auto_respond = true;
                    send_msg_to_user(fromUserNameStr, "温馨提示：机器人已开启。", true);
                }
                else if(content.startsWith("机器人关闭")) {
                    m_auto_respond = false;
                    send_msg_to_user(fromUserNameStr, "温馨提示：机器人已关闭。", true);
                }
            }
#else
            if(content.startsWith(":") || content.startsWith("：")) {
                // 有人和机器人说话
                if(m_group_auto_respond)
                    robot->post(fromUserNameStr, m_senderId, content.mid(1));
            }
#endif

            qDebug() << QDateTime::fromTime_t(createTime).toString("hh:mm:ss") << "[" << from_nickName << "] ---> [" << senderName << "]" << content;
		}
		else {
			// 2.联系人发给我
            qDebug() << QDateTime::fromTime_t(createTime).toString("hh:mm:ss") << "[" << from_nickName << "]--->" << content;

            if(m_private_auto_respond)
                robot->post("", fromUserNameStr, content);
		}
	}
}

void Login_Manager::msg_ok(QStringList sync_key)
{
	m_sync_key = sync_key;

    sync_check->getV2(m_uin, m_sid, m_skey, m_device_id, m_sync_key);
}

void Login_Manager::robot_respond(QString userid, QString context)
{
    send_msg_to_user(userid, context);
}

void Login_Manager::send_msg_to_user(QString userid, QString context)
{
    qDebug() << QTime::currentTime().toString("hh:mm:ss") << "[" << contact_info->getNickName(userid) << "] <---" << context;

    send_msg->postV2(m_uin, m_sid, m_skey, m_device_id, m_loginUserName, userid, context);
}
